package io.bytes;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import io.TestResourcesDirectory;

/**
 * 缓冲输入输出字节流（包含缓冲区）的演示
 * 
 * @author fidel
 */
public class BufferedDemo {
    public static void main(String[] args) {
        File file = new File(TestResourcesDirectory.PATH + File.separator + "BytesBufferedDemo.txt");
        // try-with-resources
        try (OutputStream os = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(os);) {
            String str = "Byte stream cannot read or write Chinese characters";
            final int len = 16;
            byte[] arr = new byte[len];
            for (int i = 0; i < str.length(); i++) {
                int mod = i % len;
                arr[mod] = (byte) str.charAt(i);
                if (mod == len - 1 || i == str.length() - 1) {
                    if (mod == len - 1) {
                        // 将数组中的所有字节写入流
                        bos.write(arr);
                    } else {
                        // 将数量不足数组长度的剩余字节写入流
                        bos.write(arr, 0, mod + 1);
                    }
                }
            }
            bos.flush();
            InputStream is = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            arr = new byte[len];
            // 将从此流读入的每个字节依次赋值给数组的相应下标
            int size;
            while ((size = bis.read(arr, 0, len)) != -1) {
                for (int i = 0; i < size; i++) {
                    System.out.print((char) arr[i]);
                }
            }
            is.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
